from locust import HttpLocust, TaskSet, task
import random
from faker import Faker
from locust import HttpUser, task, between,HttpLocust
from locust import LoadTestShape
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
fake = Faker(locale='zh_CN')
import json

# def fakertime():
#     return fake.unix_time()
#
#
# def fakername():
#     return fake.company() + str('的订单') + str(random.randint(0, 999))
#
# def random_page():
#     return random.randint(1,1360)

class QuickstartUser(TaskSet):
    def on_start(self):
        pass
#
#     @task
#     def api1(self):
#         header = {
#             "Host": "market-uat.tangees.com",
#             "Connection": "keep-alive",
#             "Content-Length": "482",
#             "Accept": "*/*",
#             "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Edg/89.0.774.63",
#             "Content-Type": "application/json;charset=UTF-8",
#             "Origin": "https://market-uat.tangees.com",
#             "Sec-Fetch-Site": "same-origin",
#             "Sec-Fetch-Mode": "cors",
#             "Sec-Fetch-Dest": "empty",
#             "Accept-Encoding": "gzip, deflate, br",
#             "Accept-Language": "zh-CN,zh;q=0.9",
#             "Cookie": "monitorCustomerKey=b29c9280-1a60-48aa-8b0d-69733fc18f3d-20210526180030; webfunny_ip=61.144.146.250; webfunny_province=%E5%B9%BF%E4%B8%9C%E7%9C%81%E5%B9%BF%E5%B7%9E%E5%B8%82%E5%A4%A9%E6%B2%B3%E5%8C%BA; accountCenterSessionId=.eJw9j0tLw0AUhf_LrLuYx51X17YiNCloQNpNuHfmTh_ECE00ovjfHRRcnsP54HxfIp1xHHkQa7EwiZV4m_jWX3LNTsnIyC46CZlURgrkI4Q6mn4H-675aF-2Q_uZ5n23HZonKQ_XRu2609Lqh7m928jj_eNwvJ7g8LxZKtiXG09nsS44TLwSI3PuJ3znfn7tM_33fwc02GxAgtMGGEIg7VHZgliyiZ5ZG6sDStBaB4Uc2Afjk-XipQ2RIiUKuYRiUXpAZnbemawJomIk9ioVjJAK22oYK1-yAltM9WRSJorvH10aVio.E-vVBg.mXIXUD2ZO_A7ngXfBenCoo7cFl4",
#         }
#         # cookie = {
#         #     "accountCenterSessionId": "eJwljs1KA0EQhN9lzjnMT8_07N6ExCA4hGBA3Msy091j1LjC7sZAxHd31UNBUfBV1ZeiYx4GOalWXaSolZpeePFpvdG7x_2lW9_M3TaZ3YPW3SFd7w_Pvtvu5_SafPd-55LduKfr7dsC9n8gYuMjW6dzAbRcpQKiY87IvmryGsjoApVMiJVro0F0DmitLAKikIEYIuQQyHhjTXTWIkcM1QkJBiriIhkwSytJFCkNBwQrxB6b-nukjjIdVTuPZ1mpQYT7KX9KP3_0XFRb82la8vMk4__loF1FDk0TNHAx5JdNsNar7x8EiVPj.E6NBrw.T9q6TjIu-q0AUTJWMrQK2cZsesI"
#         # }
#         payload = {"pageNum": "1","pageSize":"10"}
#         #https://qwx-uat-mobile.tangees.com/h5/material/scriptLibrary/page
#         with self.client.post(url='/web/material/v2/file/list', headers=header,data=json.dumps(payload),
#                               catch_response=True) as response:
#             if response.status_code == 200:
#                 try:
#                     json.loads(response.text)['errCode'] == 0
#                 except:
#                     response.failure("Timeout")
#             else:
#                 response.failure(response.status_code)
#                 # response.failure("No data")
# #
#     @task(1)
#     def api2(self):
#         header = {
#             # "Host": "scrm-test.tangees.com",
#             "Connection": "keep-alive",
#             "Content-Length": "56",
#             "Accept": "*/*",
#             "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Edg/89.0.774.63",
#             "Content-Type": "application/json;charset=UTF-8",
#             "Origin": "https://qwx-uat-mobile.tangees.com",
#             "Sec-Fetch-Site": "same-origin",
#             "Sec-Fetch-Mode": "cors",
#             "Sec-Fetch-Dest": "empty",
#             # "Referer": "https://scrm-test.tangees.com/customer-migration/resign-inheritance/group",
#             "Accept-Encoding": "gzip, deflate, br",
#             "Accept-Language": "zh-CN,zh;q=0.9",
#             "authorization":"eyJzaWQiOiJZVEE0TWpZMlpqTXRNamN4T0MwME9EVmtMV0ZpTldFdE1EVXlNVEV6TkRJNE16TTIiLCJpbmRpX3VzZXJfaWQiOiI2MDNlMGMxYTk2MDRkYjAzNzRhMGVlZGMiLCJjaGFubmVsIjoid2Vjb21faDUifQ.YQpGIg.BIOjuGrXGCvwFNTzbTyoqfi0LGg",
#             "Cookie": "accountCenterSessionId=eyJzaWQiOiJZVEE0TWpZMlpqTXRNamN4T0MwME9EVmtMV0ZpTldFdE1EVXlNVEV6TkRJNE16TTIiLCJpbmRpX3VzZXJfaWQiOiI2MDNlMGMxYTk2MDRkYjAzNzRhMGVlZGMiLCJjaGFubmVsIjoid2Vjb21faDUifQ.YQpGIg.BIOjuGrXGCvwFNTzbTyoqfi0LGg",
#         }
#         # cookie = {
#         #     "accountCenterSessionId": ".eJw9j01PwzAQRP-Lzz2sP3Zt9wipeiGgIiBKL5HX3qhtSpCaAFIR_50IJI5PmhnN-1Ldsai1MhRjpBJj8oG8xqxBnLGag4FIOWQbjDMxG01AiAk1Ijmy2dueOKelm0UCIYmG4jJkKhjYYDGlMAiKsdYyWxEDQWe06DxLcU6iTWDVSuVDGkc5L2c-hRceRUo3pQ_p5reusFr36TzJSnX9RabDP75PcvlzINBeknPgNacMzI4XlRKWrek30J7uX9unnWmbzVw3-1N9C9BeH4e7ZnOtq3reb5_hYbvDuroZ9tXLoL5_ANzIU4Q.E6G69g.MwjpoEh3n2s28v5wq2rL7tp9gDA"
#         # }
#         payload = {
# 	"title": "",
# 	"materialType": 10,
# 	"pageNum": 1,
# 	"pageSize": 10
# }
#         with self.client.post(url='/h5/material/scriptLibrary/page', headers=header,data=json.dumps(payload),
#                               catch_response=True) as response:
#             if response.status_code == 200:
#                 if json.loads(response.text)['errMsg'] == 'success！':
#                     print(response.text)
#                 else:
#                     response.failure("Timeout")
#             else:
#                 response.failure("No data")

    @task(1)
    def api3(self):
        headers = {
            'Cookie': 'accountCenterSessionId=.eJw9zk9LxDAQBfDvkvMeMkkmf_YmHsqK7SJsKeulJJMJq3QrbKsFxe9uUPAyp_d7b77E-JLFXgCgj0bZHHwERO2NjFCCUVTIQUzea5mM0T4FdkXlpKIz9Toky2QBZVGWkHWyslhUJUpFgNkVqjSohC4jAFsXIEsDpXgXpMOkAQ1pEjsxM-dxiR88rm9jTmJf4rTwTrwvfPt70oJGx5iClXUbPCWIikyueCw3Xi7_ZvnNt5_91p7y9fn1bj023bW7l7JrnuTj8DB1ql_Pw0GfTwd9HHromnarPXSJ88xTxRsn8f0DSoVTqA.FBcQiA.16y2JSrbQq270aXoCOT1VJETn9c',
            'Content-Type': 'application/json', 'User-Agent': 'PostmanRuntime/7.26.8', 'Accept': '*/*',
            'Postman-Token': '1c2e9109-5e31-45d9-860f-10822ebc66a9', 'Host': 'inbound-uat.tangees.com', 'Accept-Encoding': 'gzip, deflate, br',
            'Connection': 'keep-alive', 'Content-Length': '30'}
        jsondata = {'pageSize': 10, 'pageNum': 1,'keyWord': "",'activityTimes':[]}

        # with self.client.get(url='/h5/material/v2/detail/article/1422742244649279488', headers=header, verify=False, params=param,catch_response=True) as response:
        with self.client.post(url='/jike-web/activity/page', verify=False, json=jsondata,headers=headers,
                             catch_response=True) as response:
            if response.status_code == 200:
                if json.loads(response.text)['errCode'] == 0:
                    pass
                else:
                    response.failure("Timeout")
            else:
                response.failure("No data")

    def on_stop(self):
        pass


# class StagesShape(LoadTestShape):
#     '''
#     在不同的阶段 具有不同的用户数和 产生率的 图形形状
#
#
#     参数解析:
#         stages ：字典列表，每个字典都具有下列这些键值的阶段:
#             duration -- 持续时间，  经过多少秒后，进入到下个阶段
#             users -- 总用户数
#             spawn_rate -- 产生率，即每秒启动/停止的用户数
#             stop -- 可以在特定阶段停止测试的值
#         stop_at_end -- 可以在所有阶段设置运行后停止
#
#     '''
#
#     stages = [
#         {"duration": 300, "users": 10, "spawn_rate": 10},
#         {"duration": 600, "users": 20, "spawn_rate": 10},
#         {"duration": 900, "users": 50, "spawn_rate": 20}
#     ]

    # def tick(self):
    #     run_time = self.get_run_time()
    #
    #     for stage in self.stages:
    #         if run_time < stage['duration']:
    #             tick_data = (stage['users'],stage['spawn_rate'])
    #             return tick_data
    #
    #     return None

class WebsiteUser(HttpUser):
    tasks = [QuickstartUser]
    host = "https://inbound-uat.tangees.com"
    # host = "https://qwx-uat-mobile.tangees.com"
    wait_time = between(1,1)#多少秒用户发起1次请求



if __name__ == "__main__":
    import os

    os.system("locust -f locust_2.py --web-host=127.0.0.1 --master")
    #locust -f locust_2.py --web-host=127.0.0.1 --worker 分布式